package cn.kgc.web;

import org.apache.commons.lang.math.RandomUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RequestMapping("/upload")
@Controller
public class UploadController {

    @RequestMapping("/file")
    @ResponseBody
    public Map<String,String> uploadFile(HttpServletRequest request, MultipartFile a_logoPicPath){
        Map<String,String> map = new HashMap<>();
        //生成唯一的图片名
        String fileName = System.currentTimeMillis()+ RandomUtils.nextInt(1000000)+".jpg";
        //获取服务器上/statics/uploadfiles目录的绝对路径
        String dir = request.getServletContext().getRealPath("/statics/uploadfiles");
        System.out.println("dir = " + dir);
        //准备目标文件
        File destFile = new File(dir,fileName);
        //将文件保存到硬盘上
        try {
            a_logoPicPath.transferTo(destFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //返回结果
        map.put("logoPicPath",fileName);
        map.put("logoLocPath",dir+"\\"+fileName);
        return map;
    }
}
